<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">


      <el-form-item label="订单状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择订单状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_order_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="客户编号" prop="wid">
        <el-input
          v-model="queryParams.wid"
          placeholder="请输入客户编号"
          clearable
          @input="queryParams.wid = queryParams.wid.replace(/\D/g,'')"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户名称" prop="userNickName">
        <el-input
          v-model="queryParams.userNickName"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="收货人" prop="receiverName">
        <el-input
          v-model="queryParams.receiverName"
          placeholder="请输入收货人名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单编号" prop="outerOrderNo">
        <el-input
          v-model="queryParams.outerOrderNo"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建人" prop="createBy">
        <el-input
          v-model="queryParams.createBy"
          placeholder="请输入创建人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="收货电话" prop="receiverMobile">
      <el-input
        v-model="queryParams.receiverMobile"
        placeholder="请输入收货电话"
        clearable
        @keyup.enter.native="handleQuery"
      />
    </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss"
          clearable
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:orderInfo:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:orderInfo:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-tooltip content="只删除【草稿】或【作废】状态订单" placement="top">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['business:orderInfo:remove']"
          >删除
          </el-button>
        </el-tooltip>
      </el-col>
      <el-col :span="1.5">
        <el-tooltip content="只恢复【删除】状态订单" placement="top">
        <el-button
          type="success"
          plain
          icon="el-icon-refresh"
          size="mini"
          :disabled="multiple"
          @click="restoreStatus"
          v-hasPermi="['business:orderInfo:restoreStatus']"
        >恢复</el-button>
        </el-tooltip>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:orderInfo:export']"
        >导出</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-copy-document"
          size="mini"
          :disabled="multiple"
          @click="handleBatchCopy"
          v-hasPermi="['business:orderInfo:add']"
        >批量复制</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-position"
          size="mini"
          :disabled="multiple"
          @click="sendOrderInfo"
          v-hasPermi="['business:orderInfo:send']"
        >发送</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-tooltip content="只取消【生效已发送】状态订单" placement="top">
        <el-button
          type="info"
          plain
          icon="el-icon-copy-document"
          size="mini"
          :disabled="multiple"
          @click="sendCancelStatus"
          v-hasPermi="['business:orderInfo:sendCancelStatus']"
        >作废</el-button>
        </el-tooltip>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-truck"
          size="mini"
          :disabled="multiple"
          @click="sendLogistics"
          v-hasPermi="['business:orderInfo:logistics']"
        >发货</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-success"
          size="mini"
          :disabled="multiple"
          @click="sendFinishStatus"
          v-hasPermi="['business:orderInfo:finish']"
        >完成</el-button>
      </el-col>



      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderInfoList" @selection-change="handleSelectionChange" show-summary
              :summary-method="getSummaries" border  height="650">
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column
        label="序号"
        type="index"
        width="50"
        align="center"
        :index="(i) => (pageSize * (pageNum - 1)) + i + 1"
      />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180"  sortable>
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="订单编号" align="center" prop="outerOrderNo" width="100"/>
      <el-table-column label="订单状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_order_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="客户编号" align="center" prop="wid" width="110"/>
      <el-table-column label="客户名称" align="center" prop="userNickName" width="120"/>
      <el-table-column label="客户姓名" align="center" prop="remark6" width="120"/>
      <el-table-column label="订单金额" align="center" prop="totalAmount" />
      <el-table-column label="应付金额" align="center" prop="shouldPayAmount" />
      <el-table-column label="抹零金额" align="center" prop="remark4" />
      <el-table-column label="商品数量" align="center" prop="orderNum" />
      <el-table-column label="积分" align="center" prop="remark2" />
      <el-table-column label="收货人" align="center" prop="receiverName" />
      <el-table-column label="收货电话" align="center" prop="receiverMobile" />
      <el-table-column label="修改时间" align="center" prop="updateTime" width="180" sortable>
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改人" align="center" prop="updateBy" />
      <el-table-column label="收款方式" align="center" prop="remark1" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_order_remark1" :value="scope.row.remark1"/>
        </template>
      </el-table-column>
      <el-table-column label="订单备注" align="center" prop="remark" width="120"/>
      <el-table-column label="省" align="center" prop="province" />
      <el-table-column label="市" align="center" prop="city" />
      <el-table-column label="区/县" align="center" prop="county" />
      <el-table-column label="详细地址" align="center" prop="address" width="120"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleDetails(scope.row)"
            v-hasPermi="['business:orderInfo:edit']"
          >详情</el-button>

          <!--  <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['business:orderInfo:remove']"
            >删除</el-button>-->

        </template>
      </el-table-column>
    </el-table>



    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单管理对话框 -->
<!--    <el-dialog :title="title" :visible.sync="open" width="1800px" append-to-body destroy-on-close>-->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1800px"
      append-to-body
      destroy-on-close
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">

        <el-row>
          <el-col :span="6">
            <el-form-item label="客户编号" prop="wid">
              <el-autocomplete
                popper-class="my-autocomplete"
                v-model="form.wid"
                placeholder="请输入客户编号"
                :fetch-suggestions="querySearch"
                @select="handleSelect"
                @clear="handleClear"
                clearable
              ><el-button slot="append" icon="el-icon-search" @click="showCustomerDialog"></el-button>
              </el-autocomplete>
            </el-form-item>


          </el-col>
          <el-col :span="6">
            <el-form-item label="客户姓名" prop="remark6">
              <el-input v-model="form.remark6" :disabled="isEditMode"  />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="收货人名称" prop="receiverName">
              <el-input v-model="form.receiverName" placeholder="请输入收货人名称" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="收货人电话" prop="receiverMobile">
              <el-input v-model="form.receiverMobile" placeholder="请输入收货人电话"
                        maxlength="11"
                        oninput="this.value = this.value.replace(/[^0-9]/g, '')" />
            </el-form-item>
          </el-col>
        </el-row>




             <el-row>
               <el-col :span="6">
               <el-form-item label="省" prop="province">
                 <el-input v-model="form.province" placeholder="请输入收货省" />
               </el-form-item>
               </el-col>
               <el-col :span="6">
               <el-form-item label="市" prop="city">
                 <el-input v-model="form.city" placeholder="请输入收货城市" />
               </el-form-item>
               </el-col>
               <el-col :span="6">
               <el-form-item label="区/县" prop="county">
                 <el-input v-model="form.county" placeholder="请输入收货区/县" />
               </el-form-item>
               </el-col>
               <el-col :span="6">
               <el-form-item label="收款方式" prop="remark1">
                 <el-select v-model="form.remark1"  >
                   <el-option
                     v-for="dict in dict.type.sys_order_remark1"
                     :key="dict.value"
                     :label="dict.label"
                     :value="dict.value"
                   ></el-option>
                 </el-select>
               </el-form-item>
               </el-col>
               </el-row>


        <!-- 修改地址输入部分 -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="详细地址" prop="address">
              <el-input
                v-model="form.address"
                placeholder="请输入详细地址"

              >
                <el-button slot="append" icon="el-icon-search" @click="parseAddress">解析</el-button>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>


        <el-form-item label="订单备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>

        <el-divider content-position="center">订单详情信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteOrderInfoDetail">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleBatchAddGoods">添加商品</el-button>
          </el-col>
        </el-row>

        <el-table
          :data="orderInfoDetailList"
          row-key="skuBarCode"
          :row-class-name="rowOrderInfoDetailIndex"
          @selection-change="handleOrderInfoDetailSelectionChange"
          ref="orderInfoDetail"
          border
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50" />


          <el-table-column label="商品ID" prop="goodsId" width="220">
            <template slot-scope="scope">
              <el-input v-model="scope.row.goodsId" :disabled="true">
                <el-button slot="append" icon="el-icon-search" @click="showGoodsDialog(scope.row)"></el-button>
              </el-input>
            </template>
          </el-table-column>

          <!-- 商品名称 -->
          <el-table-column label="商品名称" prop="title" :min-width="calcColumnWidth('title')" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.title }}
            </template>
          </el-table-column>

          <!-- 规格名称 -->
          <el-table-column label="规格名称" prop="specValueName" :min-width="calcColumnWidth('specValueName')" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.specValueName }}
            </template>
          </el-table-column>

          <!-- 原单价 -->
          <el-table-column label="原单价" prop="unitPrice"  show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.unitPrice }}
            </template>
          </el-table-column>

          <!-- 商品价格（可编辑） -->
          <el-table-column label="商品价格" prop="salePrice" width="150">
            <template slot-scope="scope">
              <el-input
                v-model.trim="scope.row.salePrice"
                placeholder="请输入价格"
                @blur="validateAMt(scope.row)"
                @input="updateAmount(scope.row)"
                :rules="[{ required: true, message: '商品价格不能为空', trigger: 'blur' }]"
              />
            </template>
          </el-table-column>

          <!-- 商品数量（可编辑） -->
          <el-table-column label="商品数量" prop="skuNum" width="150">
            <template slot-scope="scope">
              <el-input
                v-model.trim="scope.row.skuNum"
                placeholder="请输入数量"
                @input="val => handleSkuNumInput(scope.row, val)"
                @blur="validateQuantity(scope.row)"
              />
            </template>
          </el-table-column>


          <!-- 抹零金额（可编辑） -->
          <el-table-column label="抹零金额" prop="zeroAmount" min-width="150" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-input v-model="scope.row.zeroAmount"
                        placeholder="请输入抹零金额"
                        @blur="validateZeroAmount(scope.row)"
                        @input="updateAmount(scope.row)" />
            </template>
          </el-table-column>

          <!-- 金额 -->
          <el-table-column label="金额" prop="amount" min-width="150" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.amount }}
            </template>
          </el-table-column>

          <!-- 规格编码 -->
          <el-table-column label="规格编码" prop="skuCode" min-width="200" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.skuCode }}
            </template>
          </el-table-column>

          <!-- 规格条码 -->
          <el-table-column label="规格条码" prop="skuBarCode" min-width="150" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.skuBarCode }}
            </template>
          </el-table-column>

          <!-- SKUID -->
          <el-table-column label="SKUID" prop="skuId" min-width="150"show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.skuId }}
            </template>
          </el-table-column>

          <!-- 商品类目ID -->
          <el-table-column prop="categoryId" label="商品类目" width="100">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.sys_goods_category" :value="scope.row.categoryId"/>
            </template>
          </el-table-column>
        </el-table>

        <!-- 总计行 -->
        <div style="margin-top: 20px; text-align: right;">
          <span style="font-weight: bold;">总金额：</span>
          <span style="color: #f56c6c; font-size: 18px;">{{ calculateTotalAmount() }} 元</span>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 客户选择弹框 -->
<!--    <el-dialog title="选择客户" :visible.sync="customerDialogVisible" width="800px" append-to-body>-->
    <el-dialog
      title="选择客户"
      :visible.sync="customerDialogVisible"
      width="800px"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form :inline="true" :model="customerQueryParams" size="small">

        <el-form-item label="客户编号">
          <el-input v-model="customerQueryParams.wid" clearable
                    @input="customerQueryParams.wid = customerQueryParams.wid.replace(/\D/g,'')" placeholder="请输入客户编号"></el-input>
        </el-form-item>
        <el-form-item label="客户名称">
          <el-input v-model="customerQueryParams.userNickName" placeholder="请输入客户名称"></el-input>
        </el-form-item>
        <el-form-item label="客户姓名">
          <el-input v-model="customerQueryParams.name" placeholder="请输入客户姓名"></el-input>
        </el-form-item>
        <el-form-item label="客户备注">
          <el-input
            v-model="customerQueryParams.buyerRemark"
            placeholder="请输入客户备注"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleCustomerQuery">搜索</el-button>
        </el-form-item>
      </el-form>

      <el-table
        v-loading="customerLoading"
        :data="customerList"
        @row-click="handleCustomerSelect"
        highlight-current-row
      >
        <el-table-column prop="wid" label="客户编号" width="120"></el-table-column>
        <el-table-column prop="userNickName" label="客户名称"></el-table-column>
        <el-table-column prop="name" label="客户姓名"></el-table-column>
        <el-table-column prop="buyerRemark" label="客户备注"></el-table-column>
      </el-table>

      <pagination
        v-show="customerTotal>0"
        :total="customerTotal"
        :page.sync="customerQueryParams.pageNum"
        :limit.sync="customerQueryParams.pageSize"
        @pagination="getCustomerList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="customerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmCustomerSelect">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 商品选择弹窗 -->
      <el-dialog
        title="选择商品"
        :visible.sync="goodsDialogVisible"
        width="1800px"
        append-to-body
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
      <el-form :inline="true" :model="goodsQueryParams" size="small">
        <el-form-item label="规格编码">
          <el-input v-model="goodsQueryParams.skuCode" placeholder="请输入规格编码" clearable></el-input>
        </el-form-item>
        <el-form-item label="商品ID">
          <el-input v-model="goodsQueryParams.goodsId" clearable @input="goodsQueryParams.goodsId = goodsQueryParams.goodsId.replace(/\D/g,'')" placeholder="请输入商品ID"></el-input>
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input v-model="goodsQueryParams.title" placeholder="请输入商品名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="规格名称">
          <el-input v-model="goodsQueryParams.specValueName" placeholder="请输入规格名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="规格条码">
          <el-input v-model="goodsQueryParams.skuBarCode" placeholder="请输入规格条码" clearable></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleGoodsQuery">搜索</el-button>
        </el-form-item>
      </el-form>

      <el-table
        class="small-row"
        v-loading="goodsLoading"
        :data="goodsList"
        style="width: 100%"
        border
        fit
        highlight-current-row
        @selection-change="handleGoodsSelectionChange"
        @row-click="handleGoodsSelect"
        highlight-current-row
      >
        <el-table-column type="selection" width="50"></el-table-column>
        <el-table-column prop="goodsId" label="商品ID" width="140"></el-table-column>
        <el-table-column prop="title" label="商品名称" min-width="250"></el-table-column>
        <el-table-column prop="specValueName" label="规格名称" min-width="250"></el-table-column>
        <el-table-column prop="salePrice" label="销售价格" width="80"></el-table-column>
        <el-table-column prop="skuNum" label="数量" width="80"></el-table-column>
        <el-table-column prop="skuBarCode" label="规格条码" width="150"></el-table-column>
        <el-table-column prop="outerSkuCode" label="规格编码" min-width="180"></el-table-column>
        <el-table-column prop="skuId" label="SKUID" width="140"></el-table-column>
        <el-table-column prop="categoryId" label="类目" width="80">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_goods_category" :value="scope.row.categoryId"/>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="goodsTotal>0"
        :total="goodsTotal"
        :page.sync="goodsQueryParams.pageNum"
        :limit.sync="goodsQueryParams.pageSize"
        @pagination="getGoodsList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="goodsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmGoodsSelect">确 定</el-button>
      </div>
    </el-dialog>


    <!-- 订单详情 -->
<!--    <el-dialog :title="title" :visible.sync="openOne" width="1800px" append-to-body>-->
    <el-dialog
      :title="title"
      :visible.sync="openOne"
      width="1800px"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">

        <el-row>
        <el-col :span="6">
          <el-form-item label="订单编号" prop="outerOrderNo">
            <el-input v-model="form.outerOrderNo" :disabled="isEditMode" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="订单状态" prop="status">
            <el-select v-model="form.status" :disabled="isEditMode" >
              <el-option
                v-for="dict in dict.type.sys_order_status"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="客户编号" prop="wid">
            <el-input v-model="form.wid" :disabled="isEditMode" />
          </el-form-item>
        </el-col>

          <el-col :span="6">
            <el-form-item label="客户姓名" prop="remark6">
              <el-input v-model="form.remark6" placeholder="请输入客户姓名" :disabled="isEditMode"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
        <el-col :span="6">
          <el-form-item label="订单数量" prop="orderNum">
            <el-input v-model="form.orderNum" :disabled="isEditMode" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="订单金额" prop="amount">
            <el-input v-model="form.amount"  :disabled="isEditMode"/>
          </el-form-item>
        </el-col>


        <el-col :span="6">
          <el-form-item label="收货人名称" prop="receiverName">
            <el-input v-model="form.receiverName" :disabled="isEditMode"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="收货人电话" prop="receiverMobile">
            <el-input v-model="form.receiverMobile" :disabled="isEditMode" />
          </el-form-item>
        </el-col>
          </el-row>

        <el-row>
        <el-col :span="6">
          <el-form-item label="省" prop="province">
            <el-input v-model="form.province" :disabled="isEditMode" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="市" prop="city">
            <el-input v-model="form.city" :disabled="isEditMode" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="区/县" prop="county">
            <el-input v-model="form.county" :disabled="isEditMode" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="详细地址" prop="address">
            <el-input v-model="form.address" type="textarea" :disabled="isEditMode" />
          </el-form-item>
        </el-col>
          </el-row>

        <el-form-item label="订单备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :autosize="{ minRows: 4, maxRows: 10 }" :disabled="isEditMode"/>
        </el-form-item>

        <el-divider content-position="center">订单详情信息</el-divider>
        <el-table
          :data="orderInfoDetailList"
          row-key="skuBarCode"
          :row-class-name="rowOrderInfoDetailIndex"
          @selection-change="handleOrderInfoDetailSelectionChange"
          ref="orderInfoDetail"
          border
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50" />


          <el-table-column label="商品ID" prop="goodsId" width="220">
            <template slot-scope="scope">
              <el-input v-model="scope.row.goodsId" :disabled="true">
<!--                <el-button slot="append" icon="el-icon-search" @click="showGoodsDialog(scope.row)"></el-button>-->
              </el-input>
            </template>
          </el-table-column>

          <!-- 商品名称 -->
          <el-table-column label="商品名称" prop="title" :min-width="calcColumnWidth('title')" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.title }}
            </template>
          </el-table-column>

          <!-- 规格名称 -->
          <el-table-column label="规格名称" prop="specValueName" :min-width="calcColumnWidth('specValueName')" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.specValueName }}
            </template>
          </el-table-column>

          <!-- 原单价 -->
          <el-table-column label="原单价" prop="unitPrice"  show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.unitPrice }}
            </template>
          </el-table-column>

          <!-- 商品价格（可编辑） -->
          <el-table-column label="商品价格" prop="salePrice" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.salePrice" placeholder="请输入价格"  @blur="validateAMt(scope.row)"
                        @input="updateAmount(scope.row)"
                        :disabled="true"
                        :rules="[{ required: true, message: '商品价格不能为空', trigger: 'blur' }]"/>
            </template>
          </el-table-column>

          <!-- 商品数量（可编辑） -->
          <el-table-column label="商品数量" prop="skuNum" width="150">
            <template slot-scope="scope">
              <el-input
                :disabled="true"
                v-model="scope.row.skuNum"
                placeholder="请输入数量"
                @input="val => handleSkuNumInput(scope.row, val)"
                @blur="validateQuantity(scope.row)"
              />
            </template>
          </el-table-column>


          <!-- 抹零金额（可编辑） -->
          <el-table-column label="抹零金额" prop="zeroAmount" min-width="150" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-input v-model="scope.row.zeroAmount"
                        :disabled="true"
                        placeholder="请输入抹零金额"
                        @blur="validateZeroAmount(scope.row)"
                        @input="updateAmount(scope.row)" />
            </template>
          </el-table-column>

          <!-- 金额 -->
          <el-table-column label="金额" prop="amount" min-width="150" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.amount }}
            </template>
          </el-table-column>

          <!-- 规格编码 -->
          <el-table-column label="规格编码" prop="skuCode" min-width="200" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.skuCode }}
            </template>
          </el-table-column>

          <!-- 规格条码 -->
          <el-table-column label="规格条码" prop="skuBarCode" min-width="150" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.skuBarCode }}
            </template>
          </el-table-column>

          <!-- SKUID -->
          <el-table-column label="SKUID" prop="skuId" min-width="150"show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.skuId }}
            </template>
          </el-table-column>

          <!-- 商品类目ID -->
          <el-table-column prop="categoryId" label="商品类目" width="100">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.sys_goods_category" :value="scope.row.categoryId"/>
            </template>
          </el-table-column>
        </el-table>
      </el-form>

    </el-dialog>

  </div>
</template>

<script>
  import { listOrderInfo, getOrderInfo, delOrderInfo, addOrderInfo, updateOrderInfo, batchCopy,sendOrderInfo,sendLogistics,sendFinishStatus,sendCancelStatus,restoreStatus} from "@/api/business/orderInfo";
  import { listInfo, listAll} from "@/api/business/buyerInfo"; // 客户列表API
  import { listGoodsInfo } from "@/api/business/goodsInfo"; // 商品API
  import jsonp from 'jsonp'; // 导入 jsonp 库


  export default {
    name: "OrderInfo",
    dicts: ['sys_order_status', 'sys_order_remark1','sys_goods_category'],
    data() {
      return {
        form: { selectedArea: [] },
        areaOptions: [],
        amapKey: '922ef23fd17595a4f53921f3449bffc1',
        // 新增商品弹窗相关数据
        goodsDialogVisible: false,
        goodsLoading: false,
        goodsList: [],
        xxList: [],
        queryString:"",
        goodsTotal: 0,
        currentRow: null, // 当前编辑的行
        goodsQueryParams: {
          pageNum: 1,
          pageSize: 10,
          goodsId: null,
          title: null,
          skuCode:null,
          skuBarCode:null
        },
        selectedGoods: null,
        selectedGoodsList: [], // 弹框中选中的商品（多选）
        // 新增客户弹框相关数据
        customerDialogVisible: false,
        customerLoading: false,
        customerList: [],
        customerTotal: 0,
        customerQueryParams: {
          pageNum: 1,
          pageSize: 10,
          wid: null,
          userNickName: null,
          buyerRemark: '',
          name: null
        },
        customerQueryParamsOne: {
          wid: null,
        },
        selectedCustomer: null,

        isEditMode: true, // ➤ 当前是否为编辑模式
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 子表选中数据
        checkedOrderInfoDetail: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 订单管理表格数据
        orderInfoList: [],
        // 订单详情表格数据
        orderInfoDetailList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,

        openOne:false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          bosName: null,
          paymethodIds: null,
          status: null,
          remark1:null,
          name:null,
          deliveryType: null,
          wid: null,
          userNickName: null,
          receiverName: null,
          receiverMobile: null,
          createBy:null,
          params: {}
        },
        dateRange: [],  // ✅ 初始化日期范围
        pageNum: 1,
        pageSize: 10,
        // 表单校验
        rules: {

          province: [
            { required: true, message: "收货省不能为空", trigger: "blur" }
          ],
          city: [
            { required: true, message: "收货城市不能为空", trigger: "blur" }
          ],
          county: [
            { required: true, message: "收货区/县不能为空", trigger: "blur" }
          ],
          wid: [
            { required: true, message: "客户编号不能为空", trigger: "blur" }
          ],
          userNickName: [
            { required: true, message: "客户名称不能为空", trigger: "blur" }
          ],
          remark6: [
            { required: true, message: "客户姓名不能为空", trigger: "blur" }
          ],
          receiverName: [
            { required: true, message: "收货人名称不能为空", trigger: "blur" }
          ],
          receiverMobile: [
            { required: true, message: "收货人电话不能为空", trigger: "blur" },
            {
              min: 7,
              max: 11,
              message: '电话号码长度必须在 7 到 11 位之间',
              trigger: 'blur'
            }
          ],
          remark1: [
            { required: true, message: "收款方式不能为空", trigger: "blur" }
          ]
        },

      };
    },
    created() {
      this.getList();
      this.loadAllAreas();
    },
    watch: {
      'form.wid'(newVal) {
        if (!newVal) {
          // 当客户编号被清空时，自动清空客户姓名
          this.form.remark6 = '';
        }
      }
    },
    methods: {
      querySearch(queryString, cb) {
        // 如果没有输入内容，直接返回空数组，不调接口
        if (!queryString || !queryString.trim()) {
          cb([]); // 清空列表
          return;
        }
        // 如果输入不是数字，直接不请求接口
        if (!/^\d+$/.test(queryString.trim())) {
          cb([]); // 清空结果
          return;
        }
        this.customerQueryParamsOne.wid = queryString.trim();
        listAll(this.customerQueryParamsOne).then(response => {
          this.xxList = response.data;
          this.xxList = response.data.map(item => ({
            ...item,
            value: item.wid || ""   // 必须加 value
          }));
          const results = queryString
            ? this.xxList.filter(this.createFilter(queryString))
            : [];
          cb(results);
        });
      },
      createFilter(queryString) {
        return (item) => {
          if (!queryString) return false;
          const wid = (item.wid || '').toString().toLowerCase();
          const searchTerm = String(queryString).toLowerCase().trim();
          return wid.includes(searchTerm);
        };
      },


      handleSelect(item) {
        this.form.userNickName = item.userNickName;
        this.form.remark6 = item.name;
        this.form.wid = String(item.wid);
      },
      handleClear() {
        this.form.remark6 = '';
        this.form.userNickName = '';
      },
      // 动态计算某一列的最优宽度
      calcColumnWidth(key) {
        if (!this.orderInfoDetailList || this.orderInfoDetailList.length === 0) return 120;
        // 表头长度
        let maxLength = key.length;
        // 遍历该列，找到最长内容
        this.orderInfoDetailList.forEach(row => {
          if (row[key] && row[key].toString().length > maxLength) {
            maxLength = row[key].toString().length;
          }
        });
        // 每字符约14px + padding
        return maxLength * 14 + 40;
      },
      // 计算订单明细总金额
      // calculateTotalAmount() {
      //   return this.orderInfoDetailList.reduce((total, row) => {
      //     return total + (parseFloat(row.amount) || 0);
      //   }, 0);
      // },
      // 计算订单明细总金额
      calculateTotalAmount() {
        const total = this.orderInfoDetailList.reduce((total, row) => {
          const amount = parseFloat(row.amount);
          return total + (isNaN(amount) ? 0 : amount);
        }, 0);
        return total.toFixed(2); // 保留两位小数
      },
      // 处理数量输入，只允许整数
      handleSkuNumInput(row, val) {
        // 只保留数字
        const onlyInt = val.replace(/[^\d]/g, '');
        // row.skuNum = onlyInt;
        // 使用 Vue.set 或直接赋值确保响应式更新
        this.$set(row, 'skuNum', onlyInt);
        // 输入过程中也实时更新金额
        this.updateAmount(row);
      },
      // updateAmount(row) {
      //   // 把中文句号转换为英文句号
      //   let zeroAmount = row.zeroAmount.toString().replace(/。/g, '.');
      //   const price = parseFloat(row.salePrice) || 0;
      //   const qty = parseFloat(row.skuNum) || 0;
      //   row.amount = (price * qty).toFixed(2); // 保留两位小数
      //   row.zeroAmount = zeroAmount; // 更新输入值
      // },
      updateAmount(row) {
        // 确保数据存在
        const price = parseFloat(row.salePrice) || 0;
        const qty = parseInt(row.skuNum) || 0;

        // 计算金额
        const amount = (price * qty).toFixed(2);

        // 使用 $set 确保响应式更新
        this.$set(row, 'amount', amount);

        // 处理抹零金额，确保是字符串
        if (row.zeroAmount !== undefined) {
          let zeroAmount = row.zeroAmount.toString().replace(/。/g, '.');
          this.$set(row, 'zeroAmount', zeroAmount);
        }
      },
      async loadAllAreas() {
        const res = await this.jsonpRequest('https://restapi.amap.com/v3/config/district', {
          key: this.amapKey,
          keywords: '中国',
          subdistrict: 3 // 加载到区县
        });
        this.areaOptions = this.formatAreas(res.districts[0].districts);
      },
      formatAreas(list) {
        return list.map(p => ({
          name: p.name,
          code: p.adcode,
          children: p.districts.map(c => ({
            name: c.name,
            code: c.adcode,
            children: c.districts.map(d => ({
              name: d.name,
              code: d.adcode
            }))
          }))
        }));
      },
      /** ✅ JSONP 请求封装 */
      jsonpRequest(url, params) {
        return new Promise((resolve, reject) => {
          const query = Object.keys(params)
            .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
            .join('&');
          const fullUrl = `${url}?${query}`;
          jsonp(fullUrl, null, (err, data) => {
            if (err) reject(err);
            else resolve(data);
          });
        });
      },

      /** ✅ 懒加载子区域 */
      async loadAreaChildren(node, resolve) {
        const { data } = node;
        const response = await this.jsonpRequest('https://restapi.amap.com/v3/config/district', {
          key: this.amapKey,
          keywords: data.code,
          subdistrict: 1
        });
        if (response.status === '1') {
          const nodes = response.districts[0].districts.map(area => ({
            name: area.name,
            code: area.adcode,
            level: area.level,
            leaf: area.level === 'district'
          }));
          resolve(nodes);
        } else {
          resolve([]);
        }
      },

      /** ✅ 解析地址并回显 */
      async parseAddress() {
        if (!this.form.address) {
          this.$message.warning('请输入详细地址');
          return;
        }
        const response = await this.jsonpRequest('https://restapi.amap.com/v3/geocode/geo', {
          key: this.amapKey,
          address: this.form.address,
          output: 'JSON'
        });
        if (response.status === '1' && response.geocodes.length > 0) {
          const geocode = response.geocodes[0];
          const province = geocode.province;
          const city = Array.isArray(geocode.city) ? '' : geocode.city;
          const district = geocode.district;

          this.form.province = province;
          this.form.city = city || province;
          this.form.county = district;

          await this.setCascaderValue(province, city, district);

          this.$message.success('地址解析成功');
        } else {
          this.$message.error('地址解析失败');
        }
      },

      /** ✅ 根据省市区名称找到对应 code 并回显 */
      async setCascaderValue(province, city, district) {
        // 1. 找省
        const provinceNode = this.areaOptions.find(item => item.name.includes(province));
        if (!provinceNode) {
          this.$message.warning(`未找到省份：${province}`);
          return;
        }

        // ✅ 确保城市和区的 options 被加载
        const cities = await this.loadChildren(provinceNode);
        const cityNode = cities.find(item => item.name.includes(city)) || cities[0];

        let districts = [];
        let districtNode = null;
        if (cityNode) {
          districts = await this.loadChildren(cityNode);
          districtNode = districts.find(item => item.name.includes(district)) || districts[0];
        }

        // ✅ 组装选中值
        const selectedCodes = [provinceNode.code];
        if (cityNode) selectedCodes.push(cityNode.code);
        if (districtNode) selectedCodes.push(districtNode.code);

        this.form.selectedArea = selectedCodes;

        // ✅ 强制 el-cascader 刷新显示
        this.$nextTick(() => {
          const panel = this.$refs.cascader?.panel;
          if (panel && panel.calculateCheckedNodePaths) {
            panel.calculateCheckedNodePaths();
          }
        });
      },

      /** ✅ 封装加载子节点 */
      loadChildren(node) {
        return new Promise(resolve => {
          this.loadAreaChildren({ data: node }, resolve);
        });
      },
      // 校验商品数量
      validateQuantity(row) {
        if (!row.skuNum || isNaN(row.skuNum)) {
          this.$message.error('请输入有效的商品数量');
          row.skuNum = '';
          return false;
        } else if (parseInt(row.skuNum, 10) <= 0) {
          this.$message.error('商品数量必须大于0');
          row.skuNum = '';
          return false;
        }
        // 强制转整数，避免小数存进去
        row.skuNum = String(parseInt(row.skuNum, 10));
        return true;
      },
      // 校验商品价格
      validateAMt(row) {
        if (!row.salePrice || isNaN(row.salePrice)) {
          this.$message.error('请输入有效的商品价格');
          row.salePrice = '';
          return false;
        } else if (row.salePrice <= 0) {
          this.$message.error('商品价格必须大于0');
          row.salePrice = '';
          return false;
        }
        return true;
      },
      // 校验抹零金额
      validateZeroAmount(row) {
         if (row.zeroAmount < 0) {
          this.$message.error('抹零金额必须大于或0');
          row.zeroAmount = '';
          return false;
        }
        return true;
      },
      /** 弹框选择商品多选回调 */
      handleGoodsSelectionChange(val) {
        this.selectedGoodsList = val; // val是数组
      },
      /** 打开批量添加商品弹框 */
      handleBatchAddGoods() {
        this.selectedGoodsList = []; // 清空上次选择
        this.goodsDialogVisible = true;
        this.getGoodsList();         // 加载商品列表
      },
      // 显示商品选择弹窗
      showGoodsDialog(row) {
        this.currentRow = row;
        this.goodsDialogVisible = true;
        this.getGoodsList();
      },
      // 获取商品列表
      getGoodsList() {
        this.goodsLoading = true;
        listGoodsInfo(this.goodsQueryParams).then(response => {
          this.goodsList = response.rows;
          this.goodsTotal = response.total;
          this.goodsLoading = false;
        });
      },
      // 商品搜索
      handleGoodsQuery() {
        this.goodsQueryParams.pageNum = 1;
        const params = this.goodsQueryParams;
        // 防止空值调用 trim 报错
        if (params.skuBarCode) params.skuBarCode = params.skuBarCode.trim();
        if (params.specValueName) params.specValueName = params.specValueName.trim();
        if (params.skuCode) params.skuCode = params.skuCode.trim();
        if (params.title) params.title = params.title.trim();
        this.getGoodsList();
      },
      // 商品行点击
      handleGoodsSelect(row) {
        this.selectedGoods = row;
      },
      //批量新增商品确认
      confirmGoodsSelect() {
        if (!this.selectedGoodsList || this.selectedGoodsList.length === 0) {
          this.$message.warning('请先选择商品');
          return;
        }

        // 遍历选中商品，将其添加到订单详情列表
        this.selectedGoodsList.forEach(item => {
          // 判断是否已存在（通过 skuBarCode 判断）
          const exists = this.orderInfoDetailList.some(
            detail => detail.skuBarCode === item.skuBarCode
          );
          if (exists) {
            this.$message.warning(`商品【${item.skuBarCode}】已存在，请勿重复添加`);
          } else {
            // this.orderInfoDetailList.push({
            //   goodsId: item.goodsId,
            //   title: item.title,
            //   specValueName: item.specValueName,
            //   unitPrice: item.salePrice,
            //   salePrice: item.salePrice,
            //   zeroAmount: 0,             // 默认抹零金额
            //   skuCode: item.outerSkuCode,
            //   skuBarCode: item.skuBarCode,
            //   skuId: item.skuId,
            //   categoryId: item.categoryId
            // });
            // 使用 Vue.set 或 push 后立即更新视图
            this.orderInfoDetailList.push({
              goodsId: item.goodsId,
              title: item.title,
              specValueName: item.specValueName,
              unitPrice: item.salePrice,
              salePrice: item.salePrice,
              skuNum: '1', // 默认数量为1，确保是字符串
              zeroAmount: '0', // 默认抹零金额，确保是字符串
              amount: item.salePrice, // 默认金额
              skuCode: item.outerSkuCode,
              skuBarCode: item.skuBarCode,
              skuId: item.skuId,
              categoryId: item.categoryId
            });
          }
        });
        // 强制更新视图
        this.$forceUpdate();
        // // 更新表格序号
        // this.orderInfoDetailList.forEach((item, index) => item.index = index + 1);
        // // ✅ 为防止 Vue 复用旧数据，深拷贝刷新
        // this.orderInfoDetailList = JSON.parse(JSON.stringify(this.orderInfoDetailList));
        // // 关闭弹窗
        this.goodsDialogVisible = false;

        // 清空弹窗选中数据
        this.selectedGoodsList = [];
      },

      // 显示客户选择弹框
      showCustomerDialog() {
        this.customerDialogVisible = true;
        this.getCustomerList();
      },

      // 获取客户列表
      getCustomerList() {
        this.customerLoading = true;
        listInfo(this.customerQueryParams).then(response => {
          this.customerList = response.rows;
          this.customerTotal = response.total;
          this.customerLoading = false;
        });
      },
      // 客户搜索
      handleCustomerQuery() {
        this.customerQueryParams.pageNum = 1;
        this.getCustomerList();
      },

      // 客户行点击
      handleCustomerSelect(row) {
        this.selectedCustomer = row;
      },
      // 确认选择客户
      confirmCustomerSelect() {
        if (this.selectedCustomer) {
          this.form.wid = String(this.selectedCustomer.wid);
          this.form.userNickName = this.selectedCustomer.userNickName;
          this.form.remark6 = this.selectedCustomer.name;
          // 可以根据需要设置其他客户相关信息
          this.customerDialogVisible = false;
        } else {
          this.$message.warning('请先选择一个客户');
        }
      },



      /** 查询订单管理列表 */
      getList() {
        this.loading = true;
        listOrderInfo(this.queryParams).then(response => {
          this.orderInfoList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          // 重置时初始化 selectedArea
          selectedArea: [],

          outerOrderNo: null,
          payType: null,
          payTime: null,
          orderStatus: null,
          channelType: null,
          payStatus: null,
          bizSourceType: null,
          saleChannelType: null,
          outitemId: null,
          totalAmount: null,
          shouldPayAmount: null,
          payAmount: null,
          amount: null,
          orderNum: null,
          vid: null,
          bosName: null,
          processVidType: null,
          vidType: null,
          processVid: null,
          processVidName: null,
          phase: null,
          paymethodIds: null,
          remark: null,
          remark1: null,
          remark2: null,
          remark3: null,
          remark4: null,
          remark5: null,
          remark6: null,
          status: null,
          address: null,
          province: null,
          city: null,
          county: null,
          senderName: null,
          senderMobile: null,
          deliveryType: null,
          wid: null,
          userNickName: null,
          name:null,
          receiverName: null,
          receiverMobile: null,
          createTime: null,
          createBy: null,
          updateTime: null,
          updateBy: null
        };
        this.orderInfoDetailList = [];
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.queryParams.params = this.queryParams.params || {};
        if (this.dateRange && this.dateRange.length === 2) {
          // 开始时间：当天00:00:00
          this.queryParams.params.beginTime = this.dateRange[0].split(' ')[0] + ' 00:00:00';
          // 结束时间：当天23:59:59
          this.queryParams.params.endTime = this.dateRange[1].split(' ')[0] + ' 23:59:59';
        } else {
          this.queryParams.params.beginTime = null;
          this.queryParams.params.endTime = null;
        }
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.outerOrderNo)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加订单管理";
      },

      /** 详情按钮操作 */
      handleDetails(row) {
        this.reset();
        const outerOrderNo = row.outerOrderNo || this.ids
        getOrderInfo(outerOrderNo).then(response => {
          this.form = response.data;
          this.orderInfoDetailList = response.data.orderInfoDetailList;
          this.openOne = true;
          this.title = "订单详情";
        });
      },

      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const outerOrderNo = row.outerOrderNo || this.ids
        getOrderInfo(outerOrderNo).then(response => {
          this.form = response.data;
          this.orderInfoDetailList = response.data.orderInfoDetailList;

          // 修复：确保区级数据正确初始化
          this.$set(this.form, 'selectedArea', []);
          if (this.form.province) this.form.selectedArea.push(this.form.province);
          if (this.form.city) this.form.selectedArea.push(this.form.city);
          if (this.form.county) this.form.selectedArea.push(this.form.county);

          this.form.wid = String(this.form.wid);
          this.open = true;
          this.title = "修改订单管理";
        });
      },
      /** 提交按钮 */
      submitForm() {
        // 确保级联选择器的值同步到表单字段
        if (this.$refs.cascader && this.$refs.cascader.getCheckedNodes) {
          const checkedNodes = this.$refs.cascader.getCheckedNodes();
          if (checkedNodes.length > 0) {
            const labels = checkedNodes[0].pathLabels; // ['省', '市', '区']
            this.form.province = labels[0] || '';
            this.form.city = labels[1] || '';
            this.form.county = labels[2] || '';
          }
        }
        // 新增：校验skuBarCode是否重复
        const skuBarCodes = new Set();
        let hasDuplicate = false;

        this.orderInfoDetailList.forEach(item => {
          if (item.skuBarCode) {
            if (skuBarCodes.has(item.skuBarCode)) {
              hasDuplicate = true;
              this.$message.error(`规格条码 ${item.skuBarCode} 重复，请检查商品明细`);
            } else {
              skuBarCodes.add(item.skuBarCode);
            }
          }
        });

        if (hasDuplicate) return; // 存在重复时停止提交
        // 先校验所有商品明细
        let isValid = true;
        this.orderInfoDetailList.forEach(item => {
          if (!item.salePrice || !item.skuNum) {
            isValid = false;
            this.$message.error('请填写完整的商品价格和数量');
          }
          if (!item.goodsId || !item.title ) {
            isValid = false;
            this.$message.error('请选择商品信息！');
          }
        });
        if (!isValid) return;

        this.$refs["form"].validate(valid => {
          if (valid) {
            this.form.orderInfoDetailList = this.orderInfoDetailList;
            if (this.form.outerOrderNo != null) {
              updateOrderInfo(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addOrderInfo(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const outerOrderNos = row.outerOrderNo || this.ids;

        this.$modal.confirm('是否确认删除订单编号为"' + outerOrderNos + '"的数据项？').then(function() {
          return delOrderInfo(outerOrderNos);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },

      /** 批量复制按钮操作 */
      handleBatchCopy() {
        if (this.ids.length === 0) {
          this.$modal.msgError("请先选择要复制的订单");
          return;
        }

        this.$modal.confirm('确定复制选中' + this.ids.length + '条订单吗？').then(() => {
          this.loading = true;
          // 调用批量复制API
          batchCopy(this.ids).then(response => {
            this.$modal.msgSuccess("复制成功");
            this.getList();
          }).finally(() => {
            this.loading = false;
          });
        }).catch(() => {});
      },

      /** 发送按钮操作 */
      sendOrderInfo() {
        if (this.ids.length === 0) {
          this.$modal.msgError("请先选择要发送的订单");
          return;
        }
        this.$modal.confirm('确定选中' + this.ids.length + '条订单吗？').then(() => {
          this.loading = true;
          // 调用发送微盟接口
          sendOrderInfo(this.ids).then(response => {
            this.$modal.msgSuccess("发送成功");
            this.getList();
          }).finally(() => {
            this.loading = false;
          });
        }).catch(() => {});
      },

      /** 发货按钮操作 */
      sendLogistics() {
        if (this.ids.length === 0) {
          this.$modal.msgError("请先选择要发货的订单");
          return;
        }
        this.$modal.confirm('确定选中' + this.ids.length + '条订单吗？').then(() => {
          this.loading = true;
          // 调用发货微盟接口
          sendLogistics(this.ids).then(response => {
            this.$modal.msgSuccess("发货成功");
            this.getList();
          }).finally(() => {
            this.loading = false;
          });
        }).catch(() => {});
      },

      /** 完成按钮操作 */
      sendFinishStatus() {
        if (this.ids.length === 0) {
          this.$modal.msgError("请先选择要完成的订单");
          return;
        }
        this.$modal.confirm('确定选中' + this.ids.length + '条订单吗？').then(() => {
          this.loading = true;
          // 调用发货微盟接口
          sendFinishStatus(this.ids).then(response => {
            this.$modal.msgSuccess("成功");
            this.getList();
          }).finally(() => {
            this.loading = false;
          });
        }).catch(() => {});
      },

      /** 作废按钮操作 */
      sendCancelStatus() {
        if (this.ids.length === 0) {
          this.$modal.msgError("请先选择要作废的订单");
          return;
        }

        this.$modal.confirm('确定作废选中' + this.ids.length + '条订单吗？').then(() => {
          this.loading = true;
          // 调用批量复制API
          sendCancelStatus(this.ids).then(response => {
            this.$modal.msgSuccess("作废成功");
            this.getList();
          }).finally(() => {
            this.loading = false;
          });
        }).catch(() => {});
      },

      /** 恢复按钮操作 */
      restoreStatus() {
        if (this.ids.length === 0) {
          this.$modal.msgError("请先选择要恢复的订单");
          return;
        }
        this.$modal.confirm('确定恢复选中' + this.ids.length + '条订单吗？').then(() => {
          this.loading = true;
          restoreStatus(this.ids).then(response => {
            this.$modal.msgSuccess("恢复成功");
            this.getList();
          }).finally(() => {
            this.loading = false;
          });
        }).catch(() => {});
      },

      /** 订单详情序号 */
      rowOrderInfoDetailIndex({ row, rowIndex }) {
        row.index = rowIndex + 1;
      },
      /** 订单详情添加按钮操作 */
      handleAddOrderInfoDetail() {
        // 新建空对象
        let newObj = {
          skuCode: "",
          totalAmount: "",
          shouldPayAmount: "",
          payAmount: "",
          amount: "",
          description: "",
          type: "",
          salePrice: "",
          specValueName: "",
          goodsSellMode: "",
          skuId: "",
          skuNum: "",
          categoryId: "",
          goodsId: "",
          title: "",
          skuBarCode: "", // 规格条码
          unitPrice:"",
          zeroAmount:"",
          unitAmount:""
        };
        // 检查重复（如果用户上次填入的规格条码重复）
        const existingBarCodes = this.orderInfoDetailList.map(item => item.skuBarCode).filter(Boolean);
        if (newObj.skuBarCode && existingBarCodes.includes(newObj.skuBarCode)) {
          this.$message.error("规格条码已存在，请勿重复添加！");
          return;
        }
        // ✅ 如果没有重复，新增行
        this.orderInfoDetailList.push(newObj);
      },
      /** 订单详情删除按钮操作 */
      handleDeleteOrderInfoDetail() {
        if (this.checkedOrderInfoDetail.length == 0) {
          this.$modal.msgError("请先选择要删除的订单详情数据");
        } else {
          const orderInfoDetailList = this.orderInfoDetailList;
          const checkedOrderInfoDetail = this.checkedOrderInfoDetail;
          this.orderInfoDetailList = orderInfoDetailList.filter(function(item) {
            return checkedOrderInfoDetail.indexOf(item.index) == -1
          });
        }
      },
      /** 复选框选中数据 */
      handleOrderInfoDetailSelectionChange(selection) {
        this.checkedOrderInfoDetail = selection.map(item => item.index)
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('business/orderInfo/export', {
          ...this.queryParams
        }, `orderInfo_${new Date().getTime()}.xlsx`)
      },
      getSummaries(param) {
        const { columns, data } = param;
        const sums = [];
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '总计';
            return;
          }

          if (column.property === 'totalAmount') {
            const total = data.reduce((sum, item) => sum + (Number(item[column.property]) || 0), 0);
            sums[index] = `${total.toFixed(2)} 元`;  // 数字和单位合并
          } else {
            sums[index] = '';
          }
        });
        return sums;
      },
    }
  };
</script>

<style scoped>
  /* 添加一些样式来美化客户选择表格 */
  .el-table >>> .current-row {
    cursor: pointer;
    background-color: #f5f7fa;
  }

  .goods-selector .el-dialog {
    margin-top: 5vh !important;
  }

  /* 必填项标识 */
  .required-label::before {
    content: "*";
    color: #f56c6c;
    margin-right: 4px;
  }

  /* 添加级联选择器样式 */
  .el-cascader {
    width: 100%;
  }
  .small-row ::v-deep .el-table__cell {
    padding: 2px 0 !important;
  }


</style>

